package com.yp.infrastructure.shiro.utils;


import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.yp.infrastructure.common.model.BaseModel;
import com.yp.infrastructure.shiro.model.BaseCredential;
import com.yp.infrastructure.shiro.starter.SecurityConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;

import java.util.Date;


@Slf4j
public class JwtUtils {

    public static void expired(String token) {

    }

    /**
     * 解析
     *
     * @param clazz .
     * @param token .
     * @return .
     * @param <T> .
     */
    public static <T extends BaseCredential> T getCredential(Class<T> clazz, String token) {
        DecodedJWT jwt = JWT.decode(token);
        T instance = BaseModel.newInstance(clazz);
        if (null == instance) return null;
        instance.setFieldsValue(jwt);
        return instance;
    }


    /**
     * 签名
     * @param userCredential .
     * @param config .
     * @return .
     * @param <T> .
     */
    public static <T extends BaseCredential> String signToken(T userCredential, SecurityConfig config) {
        Date expiration = DateUtils.addHours(new Date(), config.getExpired());
        try {
            Algorithm algorithm = Algorithm.HMAC256(config.getSecret());
            return userCredential.getToken(algorithm, expiration);
        } catch (Exception e) {
            return null;
        }
    }

}